package main

import (
	"fmt"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"sync"
	"time"
	"wms-go/modules/m_db/wms_plugin"
)

var (
	db   *gorm.DB
	once sync.Once
)

func InitDB() {
	once.Do(func() {
		var err error
		dsn := "host=" + GetConfigHandler().GetString("db.wms.host") + " user=" + GetConfigHandler().GetString("db.wms.user") + " password=" + GetConfigHandler().GetString("db.wms.pwd") + " dbname=" + GetConfigHandler().GetString("db.wms.dbname") + " port=" + GetConfigHandler().GetString("db.wms.port") + " sslmode=disable TimeZone=Asia/Shanghai"
		db, err = gorm.Open(postgres.New(postgres.Config{
			DSN:                  dsn,
			PreferSimpleProtocol: true, // disables implicit prepared statement usage
		}), &gorm.Config{
			SkipDefaultTransaction: true,
			NamingStrategy:         schema.NamingStrategy{SingularTable: true},
			Logger:                 logger.Default.LogMode(logger.Info),
		})
		if err == nil {
			fmt.Println("数据库打开成功")
		} else {
			fmt.Println("数据库打开失败")
			return
		}
		sqlDB, err := db.DB()
		if err != nil {
			fmt.Println("通用数据库对象获取失败")
			return
		}
		sqlDB.SetMaxOpenConns(100)
		sqlDB.SetMaxIdleConns(100)
		sqlDB.SetConnMaxIdleTime(time.Hour)
		db.Use(&wms_plugin.QueryBeforePlugin{})
		db.Use(&wms_plugin.CreateBeforePlugin{})
		db.Use(&wms_plugin.UpdateBeforePlugin{})
	})
}

func GetDB() *gorm.DB {
	return db
}
